package com.heisen.uua.controller;

import com.heisen.base.constant.HttpConstant;
import com.heisen.base.entity.Api;
import com.heisen.base.exception.AuthException;
import com.heisen.redis.utils.RedisUtils;
import com.heisen.security.annotation.ApiResourceOpen;
import com.heisen.uua.service.ValidateCodeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.Principal;

@Slf4j
@RestController
public class SecurityController {

    @Autowired
    private ConsumerTokenServices consumerTokenServices;


    @Autowired
    ValidateCodeService validateCodeService;


    @Autowired
    RedisUtils redisUtils;

    @GetMapping("redis")
    public String getlister() {

         redisUtils.convertAndSend("AA","你好");
         return "1";
    }

    @GetMapping("user")
    public Principal currentUser(Principal principal) {
        return principal;
    }

    @ApiResourceOpen
    @GetMapping("captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response)  {
        validateCodeService.create(request, response);
    }

    /**
     * 退出登入
     * @param request
     * @return
     * @throws AuthException
     */
    @DeleteMapping("signout")
    public Api signout(HttpServletRequest request)  {
        log.info("【准备登出】");
        String authorization = request.getHeader(HttpConstant.HttpHeader.AUTHORIZATION);
        String token = StringUtils.replace(authorization, HttpConstant.HttpHeader.TOKEN_PREFIX, "");
        return   Api.of(consumerTokenServices.revokeToken(token)) // 退出登入
                .failMsg(HttpConstant.HttpMsg.MSG_SINGIN_OUT_FAIL)
                .OkMsg(HttpConstant.HttpMsg.MSG_SINGIN_OUT_SUCCESS)
                .build();
    }
}
